package com.rongc.client.freight.business.supply.view.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.rongc.client.core.gson.GsonHelper;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.widget.BaseInputDialog;
import com.rongc.client.freight.business.carrier.model.ConveyanceBean;
import com.rongc.client.freight.business.carrier.request.api.ConveyanceDetailApi;
import com.rongc.client.freight.business.mine.model.CarBean;
import com.rongc.client.freight.business.supply.model.CommentBean;
import com.rongc.client.freight.business.supply.request.api.SupplyModifyPriceApi;
import com.rongc.client.freight.business.supply.view.fragment.SupplyCommentListFragment;
import com.rongc.client.freight.business.supply.view.fragment.SupplyDetailFragment;
import com.rongc.client.freight.business.supply.view.fragment.SupplyFragment;
import com.rongc.client.freight.business.supply.view.fragment.UserFragment;
import com.rongc.client.freight.business.waybill.model.WayBillBean;
import com.rongc.client.freight.business.waybill.request.api.WaybillCancelApi;
import com.rongc.client.freight.business.waybill.request.api.WaybillStatusApi;
import com.rongc.client.freight.business.waybill.view.activity.WayBillNewActivity;
import com.rongc.client.freight.utils.UtilMethod;
import com.viewpagerindicator.TabPageIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.flyco.dialog.widget.NormalDialog.STYLE_TWO;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.DZF_STATUS;

/**
 * Created by Bruce on 2017/7/14.
 */
public class SupplyWaybillDetailActivity extends BaseActivity implements View.OnClickListener{

    private static final String[] CONTENT = new String[] { "车辆详情", "货主评价"};

    @Bind(R.id.pager)
    ViewPager pager;
    @Bind(R.id.indicator)
    TabPageIndicator indicator ;

    FragmentPagerAdapter adapter;
    SupplyDetailFragment mYJSFragment;
    SupplyCommentListFragment mWJSFragment;

    List<Fragment> mFragments = new ArrayList<Fragment>();
    @Bind(R.id.btn_submit)
    Button mBtnSubmit;

    ConveyanceBean conveyanceBean;
    WayBillBean wayBillBean;
    CarBean carBean;
    List<CommentBean> commentBeanList;

    SupplyFragment supplyFragment;
    UserFragment userFragment;

    NormalDialog caneldialog;
    BaseInputDialog inputDialog;
    NormalDialog qrsjDialog;
    @OnClick({R.id.btn_submit,R.id.btn_reject})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_jia:
                inputDialog.show();
                break;
            case R.id.btn_reject:
                caneldialog.show();
                break;
            case R.id.btn_submit:
                WaybillStatusApi p = new WaybillStatusApi(new WaybillStatusApi.WaybillStatusParams(
                        UniApplication.getInstance().getUserInfo().getUserId(),wayBillBean.getOrderid(), DZF_STATUS+""),
                        respWaybillListener, errorListener);
                RequestManager.getInstance().call(p);
                break;
        }
    }

    Response.Listener<JSONObject> respDetailListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                try {
                    conveyanceBean = GsonHelper.getDeserializer().fromJson(response.getString("trucksInfo"), ConveyanceBean.class);
                    carBean = GsonHelper.getDeserializer().fromJson(response.getString("driverInfo"), CarBean.class);
                    CommentBean[] commenta = GsonHelper.getDeserializer().fromJson(response.getString("replayList"), CommentBean[].class);
                    commentBeanList.clear();
                    if(commenta != null)
                        for (int i=0;i<commenta.length;i++){
                            commentBeanList.add(commenta[i]);
                        }
                    mWJSFragment.setDatas(commentBeanList);
                    mYJSFragment.setData(conveyanceBean,carBean);
                    mYJSFragment.setCar(carBean);

                    userFragment.setData(conveyanceBean.getImage(),conveyanceBean.getNick(),
                            response.optString("xiadanNumber"),response.optString("jiedanNumber"),
                            response.optJSONObject("rateInfo").optString("rate"),conveyanceBean.getPhone());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                UtilMethod.dismissProgressDialog(SupplyWaybillDetailActivity.this);
            }
        }
    };



    Response.Listener<String> respPriceListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            if (HandleCode.requestSuccess()) {

                inputDialog.cancel();
            } else {
                UtilMethod.dismissProgressDialog(SupplyWaybillDetailActivity.this);
            }
        }
    };

    Response.Listener<NullResult> respWaybillListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                mBtnSubmit.setVisibility(View.GONE);
                qrsjDialog.show();
            } else {
                UtilMethod.dismissProgressDialog(SupplyWaybillDetailActivity.this);
            }
        }
    };

    Response.Listener<NullResult> respCancelListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                caneldialog.cancel();
                finish();
            } else {
                UtilMethod.dismissProgressDialog(SupplyWaybillDetailActivity.this);
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(SupplyWaybillDetailActivity.this);
        }
    };


    @Override
    public void initData() {
        ConveyanceDetailApi p = new ConveyanceDetailApi(new ConveyanceDetailApi.ConveyanceDetailParams(
                wayBillBean.getCarId(),wayBillBean.getTrucksId()),
                respDetailListener, errorListener);
        RequestManager.getInstance().call(p);
    }

    @Override
    public void initParams() {
        wayBillBean = (WayBillBean) getIntent().getSerializableExtra("data");
    }

    @Override
    public void initView() {
        initToolbar(R.string.supply_waybill_title);

        commentBeanList = new ArrayList<>();
        mBtnSubmit.setText("确认司机");
        userFragment = (UserFragment) getSupportFragmentManager().findFragmentByTag("user");
        supplyFragment = (SupplyFragment) getSupportFragmentManager().findFragmentByTag("supply");
        supplyFragment.setListener(this);
        supplyFragment.setData(wayBillBean);

        if(mFragments != null && mFragments.size() == 0){
            mYJSFragment = SupplyDetailFragment.getInstance();
            mWJSFragment = SupplyCommentListFragment.getInstance();
            mFragments.add(mYJSFragment);
            mFragments.add(mWJSFragment);
        }

        adapter = new GoogleMusicAdapter(getSupportFragmentManager());

        pager.setAdapter(adapter);
        pager.setOffscreenPageLimit(2);

        indicator.setVisibility(View.VISIBLE);
        indicator.setViewPager(pager);

        makeCanelDialog();
        makeInputDialog();
        makeqrsjDialog();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_supply_waybill_detail;
    }


    void makeCanelDialog(){
        caneldialog = new NormalDialog(this);
        caneldialog.content("已经找到车主，您要取消吗？")
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","确定"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        caneldialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        //  取消绑定
                        WaybillCancelApi p = new WaybillCancelApi(new WaybillCancelApi.WaybillCancelParams(
                                wayBillBean.getOrderid()),
                                respCancelListener, errorListener);

                        RequestManager.getInstance().call(p);
                    }
                });
    }

    void makeInputDialog(){
        inputDialog = new BaseInputDialog(this);
        inputDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                inputDialog.cancel();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                SupplyModifyPriceApi p = new SupplyModifyPriceApi(new SupplyModifyPriceApi.SupplyModifyPriceParams(
                        wayBillBean.getGid(), inputDialog.getPrice()),
                        respPriceListener, errorListener);
                RequestManager.getInstance().call(p);
            }
        });
    }

    void makeqrsjDialog(){
        qrsjDialog = new NormalDialog(this);
        qrsjDialog.setCanceledOnTouchOutside(false);
        qrsjDialog.title("确认司机成功")
                .content("请在15分钟内支付运费到平台\n在线支付 平台护航 诚信运输")
                .btnText(new String[]{"好的"})
                .style(STYLE_TWO)
                .btnNum(1)
                .dimEnabled(true)

                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        qrsjDialog.cancel();

                        Bundle bundle = new Bundle();
                        bundle.putString("data",wayBillBean.getOrderid());
                        bundle.putInt("status",DZF_STATUS);
                        ActivityUtils.startActivity(SupplyWaybillDetailActivity.this, WayBillNewActivity.class,bundle);
                        finish();
                    }
                });
    }

    class GoogleMusicAdapter extends FragmentPagerAdapter {
        public GoogleMusicAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if(mYJSFragment == null)
                        mYJSFragment = SupplyDetailFragment.getInstance();
                    return mYJSFragment;
                case 1:
                if(mWJSFragment == null) {
                        mWJSFragment = SupplyCommentListFragment.getInstance();
                    }
                return mWJSFragment;
                default:
                    break;
            }

            return mFragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return CONTENT[position % CONTENT.length].toUpperCase();
        }

        @Override
        public int getCount() {
            return CONTENT.length;
        }
    }
}
